$(() => {
    const user = JSON.parse(sessionStorage.getItem('user'))
    $('#avatarPreview').attr('src', user.avatar)
    $('#nickName').html(user.nickName)
    let categoryAry = []
    //渲染分类列表函数
    function renderCategoryList() {
        const html = template('categoryListTpl', { data: categoryAry })
        $('#categoryListBox').html(html)
    }
    renderCategoryList()
    //页面加载渲染分类列表
    $.ajax({
        type: 'get',
        url: '/categories',
        success(res) {
            categoryAry = res
            renderCategoryList()
        },
        error() {
            console.log('获取分类信息失败!');

        }
    })
    //渲染添加分类表单函数
    function renderADDcategoryForm() {
        $('#formBox').html(template('addCategoryFormTpl'))
    }
    renderADDcategoryForm()

    //添加分类事件
    $('#formBox').on('submit', '#addCategoryForm', function () {
        const formData = $(this).serialize()
        //console.log(formData);
        $.ajax({
            type: 'post',
            url: '/categories',
            data: formData,
            success(res) {
                categoryAry.push(res)
                renderCategoryList()
                $('#addCategoryForm')[0].reset()
            },
            error(res) {
                alert(JSON.parse(res.responseText).message)
            }
        })
        return false
    })

    //编辑分类表单展示
    $('#categoryListBox').on('click', '#editBtn', function () {
        const id = $(this).attr('data-id')
        $.ajax({
            type: 'get',
            url: `/categories/${id}`,
            success(res) {
                const html = template('editCategoryFormTPL', res)
                $('#formBox').html(html)
            },
            error() {
                alert('查询分类信息失败!')
            }
        })
    })

    //取消编辑表单展示
    $('#formBox').on('click', '#cancelBtn', function () {
        renderADDcategoryForm()
    })

    //编辑表单提交事件
    $('#formBox').on('submit', '#editCategoryForm', function () {
        const id = $(this).attr('data-id')
        const formData = $(this).serialize()
        $.ajax({
            type: 'put',
            url: `/categories/${id}`,
            data: formData,
            success(res) {
                const result = categoryAry.find((v) => {
                    return v._id === res._id
                })
                Object.assign(result, res)
                renderCategoryList()
                renderADDcategoryForm()
            },
            error() {
                alert('编辑失败!')
            }
        })
        return false
    })

    //删除分类
    $('#categoryListBox').on('click', '#delBtn', function (e) {
        const id = e.target.dataset.id
        const result = confirm('您确定要删除吗?')
        if (!result) { return }
        $.ajax({
            type: 'delete',
            url: `/categories/${id}`,
            success(res) {
                categoryAry = categoryAry.filter((v) => {
                    return v._id !== res._id
                })
                renderCategoryList()
            },
            error() {
                alert('删除失败!')
            }
        })
    })

    //全选框状态
    $('#selectAll').on('change', () => {
        const status = $('#selectAll').prop('checked')
        $('#categoryListBox').find('input').prop('checked', status)
        if (status) {
            $('#batchDel').removeClass('disabled')
        } else {
            $('#batchDel').addClass('disabled')
        }
    })

    //单选框状态
    $('#categoryListBox').on('change', '#radio', function () {
        const allLength = $('#categoryListBox').find('input').length
        const selectLength = $('#categoryListBox').find('input').filter(':checked').length
        $('#selectAll').prop('checked', allLength === selectLength)
        if (selectLength <= 0) {
            $('#batchDel').addClass('disabled')
        } else {
            $('#batchDel').removeClass('disabled')
        }
    })

    //批量删除点击事件
    $('#batchDel').click(function () {
        const selectCheckbox = Array.from($('#categoryListBox').find('input').filter(':checked'))
        const ids = []
        selectCheckbox.forEach((v) => {
            ids.push(v.dataset.id)
        })
        const idsStr = ids.join('-')

        $.ajax({
            type: 'delete',
            url: `/categories/${idsStr}`,
            success(res) {
                const idsAry = []
                res.forEach((v) => {
                    idsAry.push(v._id)
                })
                categoryAry = categoryAry.filter((v) => {
                    return !idsAry.includes(v._id)
                })
                renderCategoryList()
            },
            error() {
                alert('删除失败!')
            }
        })

    })

})